package com.yjb.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yjb.common.base.constant.AuthConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 认证过滤器：
 * 把jwt解析，将用户信息、权限信息放入请求头，转发给其他微服务
 */

public class AuthFilter extends ZuulFilter {
    @Value("${security.oauth2.resource.jwt.key-value}")
    String key;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        //1.获取请求上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String authorization = Optional.ofNullable(request.getHeader("Authorization")).orElse("");
        try {
            if (StringUtils.hasText(authorization)) {
                String jwtString = authorization.split(" ")[1];
                Jwt jwt = JwtHelper.decodeAndVerify(jwtString, new MacSigner(key));
                String claims = jwt.getClaims();
                ctx.addZuulRequestHeader(AuthConstant.AUTHENTICATION, claims);
            }
        } catch (InvalidSignatureException e) {
            throw new RuntimeException("认证信息无效!!");
        }
        return null;
    }
}
